/*
 * 组件注释
 * @Author: machinist_wq
 * @Date: 2022-05-03 12:50:21
 * @LastEditors: machinist_wq
 * @LastEditTime: 2022-09-07 14:58:51
 * @Description: 上传组件
 */
import React, {
  useState,
  useRef,
  forwardRef,
  useImperativeHandle,
  Fragment,
  FC,
  Attributes,
  ForwardedRef,
} from "react";
import { Upload } from "antd";
import type { UploadProps } from "antd";
import { CloudUploadOutlined } from "@ant-design/icons";

const { Dragger } = Upload;

type ICloneProps = Partial<unknown> & Attributes;

const Index: FC<UploadProps> = forwardRef(
  (props: UploadProps, ref: ForwardedRef<unknown>) => {
    const {
      disabled = false,
      maxCount = 1,
      action = window.getUrlHref() + "/api/zjkc/file/uploadFile",
      accept = "image/*,.pdf,.png,.jpg",
      children,
      fileList,
      /* 上传以后的回调 */
      ...otherConfig
    } = props;

    const upDataRef = useRef<any>({});

    const isDisabled =
      (maxCount > 0 && maxCount <= upDataRef?.current?.fileList?.length) ||
      disabled;

    const [_props, set_props] = useState<UploadProps>(() => {
      const props = {
        fileList,
        action,
        disabled: isDisabled,
        accept,
        ...otherConfig,
      };
      if (maxCount <= 0) {
        return props;
      } else {
        return {
          ...props,
          maxCount,
        };
      }
    });

    useImperativeHandle(ref, () => ({
      set_props,
      ...(upDataRef?.current ?? {}),
    }));

    return window.isEmpty(children) ? (
      // @ts-ignore
      <Dragger {..._props} ref={upDataRef} style={{ borderRadius: 5 }}>
        <Fragment>
          <p className="ant-upload-drag-icon">
            <CloudUploadOutlined style={{ color: "rgba(0,0,0,.5)" }} />
          </p>
          <p className="ant-upload-text">
            将文件拖拽到此处，或{" "}
            <a
              style={{
                ...(isDisabled
                  ? { cursor: "not-allowed", color: "rgba(0, 0, 0, .25)" }
                  : {}),
              }}>
              点击上传
            </a>
          </p>
        </Fragment>
      </Dragger>
    ) : (
      <Upload {..._props} ref={upDataRef} style={{ borderRadius: 5 }}>
        {React.isValidElement(children)
          ? React.cloneElement(children, {
              disabled: isDisabled,
            } as ICloneProps)
          : children}
      </Upload>
    );
  }
);
export default Index;
